#include "Data.h"

// 检查表达式是否只含有一种变量、常数、运算符和幂符号
int CheckExpression(Data* data)
{
    char x = 0;
    int len1 = strlen(data->input1);
    int len2 = strlen(data->input2);
    for (int i = 0; i < len1; i++)
    {
        char ch = data->input1[i];
        if (!isdigit(ch) && !IsOperator(ch) && !IsDegree(ch))
        {
            if (x == 0)
            {
                x = ch;
            }
            else if (ch != x)
            {
                return 0;
            }
        }
    }
    for (int i = 0; i < len2; i++)
    {
        char ch = data->input2[i];
        if (!isdigit(ch) && !IsOperator(ch) && !IsDegree(ch))
        {
            if (x == 0)
            {
                x = ch;
            }
            else if (ch != x)
            {
                return 0;
            }
        }
    }
    return 1;
}

// 完成表达式加减计算
Status AddExpression(Data* data)
{
    if (!CheckExpression(data))
    {
        return ERROR;
    }
    Polynomial* p1 = InitPolynomial();
    Polynomial* p2 = InitPolynomial();
    if (!SetPolynomial(p1, data->input1) || !SetPolynomial(p2, data->input2))
    {
        DeletePolynomial(p1);
        DeletePolynomial(p2);
        return ERROR;
    }
    Polynomial* p = AddPolynomial(p1, p2);
    char* res = PolynomialToString(p);
    strcpy(data->output, res);
    DeletePolynomial(p1);
    DeletePolynomial(p2);
    DeletePolynomial(p);
    free(res);
    return FINISH;
}

// 完成表达式乘法计算
Status MultExpression(Data* data)
{
    if (!CheckExpression(data))
    {
        return ERROR;
    }
    Polynomial* p1 = InitPolynomial();
    Polynomial* p2 = InitPolynomial();
    if (!SetPolynomial(p1, data->input1) || !SetPolynomial(p2, data->input2))
    {
        DeletePolynomial(p1);
        DeletePolynomial(p2);
        return ERROR;
    }
    Polynomial* p = MultPolynomial(p1, p2);
    char* res = PolynomialToString(p);
    strcpy(data->output, res);
    DeletePolynomial(p1);
    DeletePolynomial(p2);
    DeletePolynomial(p);
    free(res);
    return FINISH;
}
